package com.lin.operatorlogrecord.factory;

import com.lin.operatorlogrecord.entity.enums.IEnumBase;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class SpringMvcEnumConvertFactory implements ConverterFactory<String, IEnumBase> {
    @Override
    public <T extends IEnumBase> Converter<String, T> getConverter(Class<T> targetType) {
        return new SpringMvcEnumConvert<>(targetType);
    }

    private static final class SpringMvcEnumConvert<R extends IEnumBase> implements Converter<String, R> {
        private final Class<R> enumClazz;

        SpringMvcEnumConvert(Class<R> enumClazz) {
            this.enumClazz = enumClazz;
        }

        @Override
        public R convert(String source) {
            try {
                Integer code = Integer.valueOf(source);
                R[] enumConstants = enumClazz.getEnumConstants();
                Method method = enumClazz.getMethod("convertIEnumBase", Integer.class);
                return (R) method.invoke(enumConstants[0], code);
            } catch (NumberFormatException e) {
                throw new NullPointerException("前端传来枚举值只支持整形");
            } catch ( NoSuchMethodException e) {
                throw new NullPointerException("该枚举没有convertIEnumBase方法");
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new NullPointerException("调用反射方法失败");
            }
        }
    }

}